package com.sfy.core.example.bootstrap;

import com.sfy.core.example.RpcApplication;
import com.sfy.core.example.config.RegistryConfig;
import com.sfy.core.example.config.RpcConfig;
import com.sfy.core.example.model.ServiceMetaInfo;
import com.sfy.core.example.model.ServiceRegisterInfo;
import com.sfy.core.example.registry.LocalRegistry;
import com.sfy.core.example.registry.Registry;
import com.sfy.core.example.registry.RegistryFactory;
import com.sfy.core.example.service.tcp.VertxTcpServer;

import java.util.List;

public class ProviderBootstrap {

    public static void init(List<ServiceRegisterInfo> serviceRegisterInfoList) throws Exception {
        // RPC初始化
        RpcApplication.init();

        // 全局配置
        final RpcConfig rpcConfig = new RpcConfig();

        // 注册服务
        for (ServiceRegisterInfo serviceRegisterInfo : serviceRegisterInfoList) {
            String serviceName = serviceRegisterInfo.getServiceName();
            // 本地注册
            LocalRegistry.registry(serviceName,serviceRegisterInfo.getImplClass());

            // 注册到服务中心
            RegistryConfig registryConfig = rpcConfig.getRegistryConfig();
            Registry registry = RegistryFactory.getInstance(registryConfig.getRegistry());
            ServiceMetaInfo serviceMetaInfo = new ServiceMetaInfo();
            serviceMetaInfo.setServiceName(serviceName);
            serviceMetaInfo.setServiceHost(rpcConfig.getServerHost());
            serviceMetaInfo.setServicePort(rpcConfig.getServerPort());
            try{
                registry.register(serviceMetaInfo);
            }catch (Exception e){
                throw new RuntimeException("服务注册失败",e);
            }
        }
        // 启动服务器
        VertxTcpServer vertxTcpServer = new VertxTcpServer();
        vertxTcpServer.doStart(9999);
    }
}
